<template>
  <el-dialog
    v-model="dialogVisible"
    title="应用市场"
    width="900px"
    :before-close="handleClose"
    class="app-market-dialog"
  >
    <div class="app-market-container">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索应用..."
          prefix-icon="el-icon-search"
          clearable
          @keyup.enter="searchApps"
        >
          <template #append>
            <el-button @click="searchApps">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
      
      <!-- 分类标签 -->
      <div class="category-tabs">
        <el-tabs v-model="activeCategory" @tab-change="handleCategoryChange">
          <el-tab-pane label="全部应用" name="all" />
          <el-tab-pane 
            v-for="category in categories" 
            :key="category.id" 
            :label="category.name" 
            :name="category.id.toString()" 
          />
        </el-tabs>
      </div>
      
      <!-- 应用列表 -->
      <div class="app-list" v-loading="loading">
        <template v-if="filteredApps.length > 0">
          <el-row :gutter="20">
            <el-col 
              v-for="app in filteredApps" 
              :key="app.id" 
              :xs="24" 
              :sm="12" 
              :md="8" 
              :lg="6" 
              class="app-item-col"
            >
              <div class="app-item" @click="viewAppDetail(app)">
                <img :src="app.icon" class="app-icon" />
                <div class="app-info">
                  <h3 class="app-name">{{ app.name }}</h3>
                  <p class="app-description">{{ app.description }}</p>
                  <div class="app-meta">
                    <span class="app-developer">{{ app.developerName }}</span>
                    <span class="app-version">v{{ app.version }}</span>
                  </div>
                </div>
                <div class="app-actions">
                  <el-button 
                    v-if="isAppInstalled(app.id)" 
                    type="success" 
                    size="small" 
                    @click.stop="openApp(app.id)"
                  >
                    打开
                  </el-button>
                  <el-button 
                    v-else 
                    type="primary" 
                    size="small" 
                    @click.stop="installApp(app)"
                  >
                    安装
                  </el-button>
                </div>
              </div>
            </el-col>
          </el-row>
        </template>
        <el-empty v-else description="暂无应用" />
      </div>
    </div>
    
    <!-- 应用详情弹窗 -->
    <el-dialog
      v-if="selectedApp"
      v-model="appDetailVisible"
      :title="selectedApp.name"
      width="700px"
      append-to-body
    >
      <div class="app-detail">
        <div class="app-header">
          <img :src="selectedApp.icon" class="app-detail-icon" />
          <div class="app-header-info">
            <h2>{{ selectedApp.name }}</h2>
            <div class="app-meta">
              <span class="app-developer">开发者: {{ selectedApp.developerName }}</span>
              <span class="app-version">版本: {{ selectedApp.version }}</span>
            </div>
            <div class="app-actions">
              <el-button 
                v-if="isAppInstalled(selectedApp.id)" 
                type="success" 
                @click="openApp(selectedApp.id)"
              >
                打开
              </el-button>
              <el-button 
                v-else 
                type="primary" 
                @click="installApp(selectedApp)"
              >
                安装
              </el-button>
              <el-button 
                v-if="isAppInstalled(selectedApp.id) && !isAppOnDesktop(selectedApp.id)" 
                @click="addToDesktop(selectedApp)"
              >
                添加到桌面
              </el-button>
              <el-button 
                v-if="isAppInstalled(selectedApp.id)" 
                type="danger" 
                @click="uninstallApp(selectedApp.id)"
              >
                卸载
              </el-button>
            </div>
          </div>
        </div>
        
        <div class="app-description">
          <h3>应用介绍</h3>
          <p>{{ selectedApp.description }}</p>
        </div>
        
        <div class="app-screenshots">
          <h3>应用截图</h3>
          <div class="screenshots-carousel">
            <el-carousel :interval="4000" type="card" height="200px">
              <el-carousel-item v-for="(_, index) in 3" :key="index">
                <div class="screenshot-placeholder">
                  <el-icon><Picture /></el-icon>
                  <span>Screenshots</span>
                </div>
              </el-carousel-item>
            </el-carousel>
          </div>
        </div>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, defineProps, defineEmits, onMounted } from 'vue'
import { Search, Picture } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useAppStore } from '@/stores/app'
import type { App, AppCategory } from '@/types/app'

const props = defineProps<{
  visible: boolean
}>()

const emit = defineEmits(['update:visible', 'close'])

const appStore = useAppStore()

// 对话框可见性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 加载状态
const loading = ref(false)

// 搜索关键词
const searchKeyword = ref('')

// 应用分类
const categories = computed(() => appStore.categories)

// 激活的分类
const activeCategory = ref('all')

// 应用列表
const allApps = ref<App[]>([])

// 过滤后的应用列表
const filteredApps = computed(() => {
  let apps = [...allApps.value]
  
  // 按分类筛选
  if (activeCategory.value !== 'all') {
    const categoryId = parseInt(activeCategory.value)
    apps = apps.filter(app => app.categoryId === categoryId)
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    apps = apps.filter(app => 
      app.name.toLowerCase().includes(keyword) || 
      app.description.toLowerCase().includes(keyword)
    )
  }
  
  return apps
})

// 应用详情相关
const appDetailVisible = ref(false)
const selectedApp = ref<App | null>(null)

// 关闭对话框
const handleClose = () => {
  emit('close')
}

// 搜索应用
const searchApps = () => {
  // 保持在同一分类下搜索
  // 搜索逻辑通过计算属性实现
}

// 处理分类变更
const handleCategoryChange = (categoryId: string) => {
  // 清空搜索关键词
  searchKeyword.value = ''
}

// 获取所有应用
const fetchAllApps = async () => {
  loading.value = true
  try {
    // 假设在实际环境中会从API获取数据
    // 这里使用模拟数据
    await appStore.initAppData()
    allApps.value = appStore.installedApps
  } catch (error) {
    ElMessage.error('获取应用列表失败')
    console.error('Failed to fetch apps:', error)
  } finally {
    loading.value = false
  }
}

// 检查应用是否已安装
const isAppInstalled = (appId: number) => {
  return appStore.isAppInstalled(appId)
}

// 检查应用是否在桌面
const isAppOnDesktop = (appId: number) => {
  return appStore.isAppOnDesktop(appId)
}

// 查看应用详情
const viewAppDetail = (app: App) => {
  selectedApp.value = app
  appDetailVisible.value = true
}

// 安装应用
const installApp = async (app: App) => {
  try {
    await appStore.installApp(app)
    ElMessage.success('应用安装成功')
  } catch (error) {
    ElMessage.error('应用安装失败')
  }
}

// 卸载应用
const uninstallApp = async (appId: number) => {
  try {
    await appStore.uninstallApp(appId)
    ElMessage.success('应用卸载成功')
    
    // 如果当前查看的就是被卸载的应用，关闭详情
    if (selectedApp.value && selectedApp.value.id === appId) {
      appDetailVisible.value = false
    }
  } catch (error) {
    ElMessage.error('应用卸载失败')
  }
}

// 添加到桌面
const addToDesktop = (app: App) => {
  appStore.addToDesktop(app)
  ElMessage.success('已添加到桌面')
}

// 打开应用
const openApp = (appId: number) => {
  appStore.openApp(appId)
  
  // 打开后关闭应用市场
  dialogVisible.value = false
}

onMounted(() => {
  fetchAllApps()
})
</script>

<style scoped>
.app-market-dialog {
  display: flex;
  flex-direction: column;
}

.app-market-container {
  display: flex;
  flex-direction: column;
  min-height: 500px;
}

.search-bar {
  margin-bottom: 20px;
}

.category-tabs {
  margin-bottom: 20px;
}

.app-list {
  flex: 1;
}

.app-item-col {
  margin-bottom: 20px;
}

.app-item {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;
  cursor: pointer;
}

.app-item:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  transform: translateY(-2px);
}

.app-icon {
  width: 80px;
  height: 80px;
  object-fit: contain;
  margin: 15px auto;
}

.app-info {
  padding: 15px;
  flex: 1;
}

.app-name {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: 600;
}

.app-description {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.app-meta {
  display: flex;
  justify-content: space-between;
  color: #909399;
  font-size: 12px;
}

.app-actions {
  padding: 10px 15px;
  border-top: 1px solid #f2f6fc;
  text-align: right;
}

/* 应用详情样式 */
.app-detail {
  padding: 0 20px;
}

.app-header {
  display: flex;
  margin-bottom: 30px;
}

.app-detail-icon {
  width: 100px;
  height: 100px;
  object-fit: contain;
  margin-right: 20px;
}

.app-header-info {
  flex: 1;
}

.app-header-info h2 {
  margin-top: 0;
  margin-bottom: 10px;
}

.app-header-info .app-meta {
  margin-bottom: 15px;
}

.app-header-info .app-meta span {
  margin-right: 15px;
}

.app-description h3,
.app-screenshots h3 {
  border-left: 4px solid #409eff;
  padding-left: 10px;
  font-size: 16px;
}

.screenshots-carousel {
  margin-top: 20px;
}

.screenshot-placeholder {
  height: 100%;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
}

.screenshot-placeholder .el-icon {
  font-size: 40px;
  margin-bottom: 10px;
}
</style> 